package per.turtle.system.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.core.web.page.TableDataInfo;
import per.turtle.common.excel.annotation.ResponseExcel;
import per.turtle.common.excel.annotation.Sheet;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.system.entity.SysConfig;
import per.turtle.system.service.ISysConfigService;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author turtle
 */
@AllArgsConstructor
@RequestMapping("config")
@RestController
@Tag(name = "配置管理", description = "config_配置管理模块")
public class SysConfigController extends BaseController {

    private final ISysConfigService configService;

    @Operation(summary = "新增参数配置", description = "新增参数配置")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize(hasPermission = "system:config:add")
    public CommonResult<?> add(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return CommonResult.error("新增参数【" + config.getConfigName() + "】失败，参数键名已存在");
        }
        return result(configService.insertConfig(config));
    }

    @Operation(summary = "修改参数配置", description = "修改参数配置")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:config:edit")
    @PutMapping
    public CommonResult<?> edit(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return CommonResult.error("修改参数【" + config.getConfigName() + "】失败，参数键名已存在");
        }
        return result(configService.updateConfig(config));
    }

    @Operation(summary = "导出参数配置", description = "导出参数配置")
    @Log(title = "参数管理", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    @PreAuthorize(hasPermission = "system:config:export")
    @ResponseExcel(name = "参数配置", sheets = @Sheet(sheetName = "参数数据"))
    public List<SysConfig> export(HttpServletResponse response, @RequestBody SysConfig config) {
        return configService.selectConfigList(config);
    }

    @Operation(summary = "根据参数键名查询参数配置值（优先使用）", description = "根据参数键名查询参数配置值（优先使用）")
    @GetMapping("getByKey/{configKey}")
    @PreAuthorize(hasPermission = "system:config:query")
    public CommonResult<String> getConfigByKey(@PathVariable String configKey) {
        return CommonResult.success("操作成功", configService.selectConfigValueByKey(configKey));
    }

    @Operation(summary = "根据参数编号获取详细信息", description = "根据参数编号获取详细信息")
    @GetMapping("getById/{configId}")
    @PreAuthorize(hasPermission = "system:config:query")
    public CommonResult<SysConfig> getInfo(@PathVariable Long configId) {
        return CommonResult.success(configService.selectConfigById(configId));
    }

    @Operation(summary = "获取参数配置列表或分页", description = "获取参数配置列表或分页（区别于是否传入分页参数）")
    @PostMapping("list")
    @PreAuthorize(hasPermission = "system:config:list")
    public TableDataInfo<SysConfig> list(@RequestBody SysConfig config) {
        List<SysConfig> list = startPage(s -> configService.selectConfigList(config));
        return getDataTable(list);
    }

    @Operation(summary = "刷新参数缓存", description = "刷新参数缓存")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @PostMapping("refreshCache")
    @PreAuthorize(hasPermission = "system:config:remove")
    public CommonResult<Void> refreshCache() {
        configService.resetConfigCache();
        return CommonResult.success();
    }

    @Operation(summary = "删除参数配置", description = "删除参数配置")
    @DeleteMapping("{configIds}")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPermission = "system:config:remove")
    public CommonResult<Void> remove(@PathVariable Long[] configIds) {
        for (Long configId : configIds) {
            configService.deleteConfig(configService.selectConfigById(configId));
        }
        return CommonResult.success();
    }

}
